<?php
if (!defined("_INDEX")) { header("Location: /"); die; }

$errors = array();

$news_id = $route->getAdminId();
$news = $db->getRow("select * from `news` where `news_id` = '$news_id' and `user_id` = '".$user->getUserId()."' limit 1");
if (!$news)
	goToPage("/coordinator/content/list");

$news_tags = $db->getColumn("select `T`.`name` from `tags` as `T`,`news_tags` as `NC` where `T`.`tag_id` = `NC`.`tag_id` and `NC`.`news_id` = '$news_id'");

if (UV::readMQ($route->POST("act")) == 'post')
{
	$user_id = $user->getUserId();
	$title = UV::readMQ($route->POST("title"));
	$preview = UV::readMQ($route->POST("preview"));
	$text = UV::readMQ($route->POST("full"));
	$tags = UV::readMQ($route->POST("tags"));
	$mediablock = UV::readBool($route->POST("mediaOn")) ? 1 : 0;
	$crop_preview = $mediablock ? UV::readMQ($route->POST("crop_preview")) : "";
	$link = UV::readMQ($route->POST("link"));
	$status = UV::readMQ($route->POST("status"));
	$time = strtotime(UV::readMQ($route->POST("date")));
	$order = UV::readInt($route->POST("order")) ? UV::readInt($route->POST("order")) : 0;
	
	$query = "update `news` set `title`='$title',`preview`='$preview',`text`='$text',`tags`='$tags',`mediablock`='$mediablock',`crop_preview`='$crop_preview',`link`='$link',`status`='$status',`time`='$time',`order`='$order' where `news_id` = '$news_id' limit 1";
	if ($db->sendQuery($query))
	{
		// tags
		$db->sendQuery("delete from `news_tags` where `news_id` = '$news_id'");
		$tags = explode(",",$tags);
		foreach ($tags as $tag){
			$e_tag = preg_replace('/ +/',' ',trim($tag));
			if ($e_tag != "")
			{
				$is_tag = $db->getCell("select `tag_id` from `tags` where `name` = '$e_tag'");
				if (!$is_tag){
					$db->sendQuery("insert into `tags` values(NULL,'$e_tag')");
					$is_tag = mysql_insert_id();
				}
				$db->sendQuery("insert into `news_tags` values (NULL,'$is_tag','$news_id')");
			}
		}
		
		$path_name = MAIN_DIR.DS."files".DS."img".DS."news".DS.$news_id;
		
		// загружаем фотки
		if (isset($_FILES['photo']['tmp_name']) && $_FILES['photo']['tmp_name'] != "")
		{
			if (!is_dir($path_name))
				mkdir($path_name);
			if (!is_dir($path_name.DS."small"))
				mkdir($path_name.DS."small");
			if (!is_dir($path_name.DS."big"))
				mkdir($path_name.DS."big");
			
			$photo_size = getimagesize($_FILES['photo']['tmp_name']);
			$photo_name = "x_".time().".".substr(strrchr($_FILES['photo']['name'], '.'), 1);
			$photo = resizeImg($_FILES['photo']['tmp_name'],210,150,$path_name.DS."small".DS.$photo_name);
			if ($photo === true)
				resizeImg($_FILES['photo']['tmp_name'],$photo_size[0],$photo_size[1],$path_name.DS."big".DS.$photo_name);
		}
		
		// удаляем старую медиа-картинку
		/* if ((isset($_FILES['src']['tmp_name']) && $_FILES['src']['tmp_name'] != "") || $route->POST("img_src") != "") // если выбрали новое изображение - удаляем старое
		{
			if (is_file($path_name.DS."media.jpg"))
				unlink($path_name.DS.$file);
		} */
		
		// грузим новую медиа-картинку
		if ($mediablock)
		{
			if (!is_dir($path_name))
				mkdir($path_name);
			
			if (isset($_FILES['src']['tmp_name']) && $_FILES['src']['tmp_name'] != "")
			{
				$media_photo = resizeImg($_FILES['src']['tmp_name'],693,290,$path_name.DS."media.jpg");
				if ($media_photo !== true)
					$errors[] = "Изображение слишком маленькое и не было загружено";
			}
			elseif ($img_src = UV::readMQ(strip_tags($route->POST("img_src"))))
			{
				$img_name = tempnam(DS."tmp".DS, "x_");
				$handle = fopen($img_name, "w");
				fwrite($handle,file_get_contents($img_src));
				fclose($handle);
				
				$media_photo = resizeImg($img_name,693,290,$path_name.DS."media.jpg");
				if ($media_photo !== true)
					$errors[] = "Изображение слишком маленькое и не было загружено";
			}
		}
	}
	else
		$errors[] = "Ошибка редактирования новости";
	if (count($errors) == 0)
		goToPage("/coordinator/content/list");
}

require_once COORDINATOR.DS."head.php";
?>
<link href="/files/js/redactor/css/redactor.css" rel="stylesheet" type="text/css" />
<script type='text/javascript' src='/files/js/redactor/redactor.js'></script>
<script type='text/javascript'>
$(document).ready(function(){	
	$('#preview_news').redactor({
		image_upload: "/coordinator/content/upload"
	});
	$('#full_news').redactor({
		image_upload: "/coordinator/content/upload"
	});
	
	$("#show_preview").click(function(){
		$("#preview_title").val($("#title").val());
		$("#preview_preview").val($("#preview_news").val());
		$("#preview_link").val($("#link").val());
		$("#preview_text").val($("#full_news").val());
		$("#preview_tags").val($("#tags").val());
		$("#previewForm").submit();
	});
	
	$("#tag_list").change(function(){
		if ($(this).val() != ''){
			var tag_str = $.trim($("#tags").val());
			var tag_ar = tag_str.split(",");
			for (tag in tag_ar)
				tag_ar[tag] = $.trim(tag_ar[tag]);
			var exists = false;
			for(var i = 0, l = tag_ar.length; i < l; i++){
				if (tag_ar[i] == $(this).val()){
					exists = true;
					break;
				}
			}
			if (!exists){
				if (tag_str != '' && tag_str[tag_str.length-1] != ','){
					tag_str += ",";
				}
				tag_str += $(this).val();
				$("#tags").val(tag_str);
			}
		}
	})
	
	$("#mediaOn").click(function(){
		if ($(this).attr('checked') == 'checked')
			$("#mediablock *:not(#mediaOn)").removeAttr('disabled');
		else
			$("#mediablock *:not(#mediaOn)").attr('disabled','disabled');
	})
});
</script>

<div class="submenu_container">
	<a class="submenu_button all_news" href='/coordinator/content/list'>Список новостей</a>
	<a class="submenu_button add_news" href='/coordinator/content/add'>Добавить новость</a>
	<a class="submenu_button submenu_button_active">Редактирование новости</a>
</div>
<?php
if (count($errors) > 0)
	echo "<p style='color:red'>".implode("<br />",$errors)."</p>";
?>
<h3>Редактирование новости</h3>
<div id="contentaddnews">
	<form method='post' enctype="multipart/form-data">
		<input type="hidden" name="act" value='post' />
		<div class="left label clear"><label for='title'>Заголовок</label></div><div class="right"><input type="text" id="title" name="title" value='<?php echo $news['title']?>' /></div>
		<div class="left label clear"><label for='tags'>Теги</label></div><div class="right"><input type="text" id="tags" name="tags" value='<?php echo implode(",",$news_tags); ?>' /></div>
		<div class="left label clear"><label for='tags'>Список тегов</label></div><div class="left" style="margin: 2px 0 0 18px;">
			<select id='tag_list'>
				<option value=''>Выберите тег</option><?php
				$query = "select `T`.`name`
					from `tags` as `T`
					left join `news_tags` as `NT` using (`tag_id`)
					group by `T`.`tag_id` having count(`NT`.`tag_id`) > 0 order by count(`NT`.`tag_id`) desc,`name`";
				$tag_list = $db->getTable($query);
				echo selectCreate($tag_list,"name","name");
			?></select>
		</div>
		<div class="clear"><label for='date'>Дата</label><input style="width:100px;margin: 0 74px" type="text" id="date" name="date" value='<?php echo date("d.m.Y",$news['time']); ?>' /></div>
		<div class="clear"><label for='order'>Приоритет</label><input style="width:100px;margin: 0 34px" type="text" id="order" name="order" value='<?php echo $news['order']; ?>' /></div>
		<div class="clear">
			<label for='order'>Статус</label>
			<input style="margin-left: 60px" type="radio" name="status" value='placed' <?php if ($news['status'] != 'not') echo "checked='checked'"; ?> /> Размещено
			<input style="margin-left: 10px" type="radio" name="status" value='not' <?php if ($news['status'] == 'not') echo "checked='checked'"; ?> /> В черновиках
		</div>
		<div class="left label clear">Краткое содержание</div>
		<div class="clear"><textarea id='preview_news' name='preview'><?php echo $news['preview']?></textarea></div>
		<div class="left label clear">Текст новости</div>
		<div class="clear"><textarea id='full_news' rows='1' name='full'><?php echo $news['text']?></textarea></div>
		<div class='photos'>
			<label for='photo'>Картинки</label> <input type='file' name='photo' id='photo' />
			<?php
				$photos_path = MAIN_DIR.DS."files".DS."img".DS."news".DS.$news_id.DS."small";
				if (is_dir($photos_path))
				{
					$imgs = array();
					$handle = opendir($photos_path);
					
					while (false !== ($file = readdir($handle)))
						if ($file != "." && $file != "..")
							$imgs[] = $file;
					closedir($handle);
					
					if (count($imgs) > 0)
					{
						$max_in_row = 4;
						echo "<table>";
						$i = 0;
						while ($i < count($imgs))
						{
							echo "<tr>";
							for ($j = 0; $j < $max_in_row && $i < count($imgs); $j++)
								echo "<td><a class='images' rel='group' href='/files/img/news/$news_id/big/".$imgs[$i]."'>
								<img style='border:1px solid black' src='/files/img/news/$news_id/small/".$imgs[$i]."' /></a><br />
								<a class='delete photo' href='/coordinator/content/delete_img?news_id=$news_id&src=".$imgs[$i++]."'>Удалить</a></td>";
							echo "</tr>";
						}
						echo "</table>";
					}
				}
			?>
		</div>
		<div id='mediablock'>
			<div class="clear label"><input type="checkbox" id='mediaOn' name="mediaOn" <?php if ($news['mediablock']) echo "checked='checked'";?> /> Разместить в медиаблоке</div>
			<div class="label"><label for='caption'>Подпись</label> <input type="text" id='caption' <?php if (!$news['mediablock']) echo "disabled='disabled'";?> name="crop_preview" value='<?php echo $news['crop_preview']; ?>' /></div>
			<div class="label" id='img_file'>
				<label for='img'>Картинка</label> <input type="file" id='img' <?php if (!$news['mediablock']) echo "disabled='disabled'";?> name="src" />
				<input type='button' onclick="$('#img_file').html($('#img_file').html())" value='Отменить' style='width:70px;height:auto' <?php if (!$news['mediablock']) echo "disabled='disabled'";?> />
			</div>
			<div class="label">
				или <label for='img_src'>Ссылка</label> <input type="text" id='img_src' <?php if (!$news['mediablock']) echo "disabled='disabled'";?> name="img_src" /></div><?php
				if ($news['mediablock'])
					echo "<br /><img src='/files/img/news/$news_id/media.jpg' border='1' />";
			?><div class='label'>
				<label for='link'>Видео</label> <input type="text" id='link' <?php if (!$news['mediablock']) echo "disabled='disabled'";?> name="link" value='<?php echo $news['link']?>' />
				<span style='font-size:9pt'>если указана ссылка, то будет показываться видео, а не картинка</span>
			</div>
		</div>
		<div class="right">
			<input type="button" id="show_preview" value="Предварительный просмотр"/> | <input type="submit" value="Опубликовать"/>
		</div>
	</form>
</div>
<form id='previewForm' target='_blank' method='post' action="/coordinator/content/preview">
	<input type='hidden' name='preview_title' id='preview_title' />
	<input type='hidden' name='preview_preview' id='preview_preview' />
	<input type='hidden' name='preview_link' id='preview_link' />
	<input type='hidden' name='preview_text' id='preview_text' />
	<input type='hidden' name='preview_tags' id='preview_tags' />
	<input type='hidden' name='preview_time' id='preview_time' value='<?php echo $news['time']; ?>' />
</form>

<?php require_once COORDINATOR.DS."footer.php"; ?>
